package com.tuling.designpattern.singleton;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @author 林瑞涛
 * @date 2021年07月05日 9:11
 */
public class LazyPattern {

    //红绿等解决通过反射创建对象（反编译可以破解该方法）
    private static boolean bolNew = false;
    private LazyPattern() {
        synchronized (LazyPattern.class){
            if(bolNew == false){
                bolNew = true;
            }else{
                throw new RuntimeException("不要试图使用反射破坏单例");
            }
        }
    }

    //volatile避免指令重排
    private volatile static LazyPattern lazyPattern;


    //双重检测模式的  懒汉式单例   DCL懒汉式
    private static LazyPattern getInstance(){

        if(lazyPattern == null){
            //不是一个原子性操作
            lazyPattern = new LazyPattern();
        }
        return lazyPattern;
    }

    //反射
    public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Field bolNew = LazyPattern.class.getDeclaredField("bolNew");
        bolNew.setAccessible(true);

        Constructor<LazyPattern> declaredConstructor = LazyPattern.class.getDeclaredConstructor(null);
        declaredConstructor.setAccessible(true);//无视私有的构造器
        LazyPattern instance1 = declaredConstructor.newInstance();
        bolNew.set(instance1,false);
        System.out.println(instance1);
        LazyPattern instance2 = declaredConstructor.newInstance();

        System.out.println(instance2);
    }
}
